﻿using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Input;
using SnakeGame.ViewModels;


namespace SnakeGame.Views
{
    /// <summary>
    /// Interaction logic for PlayerPage.xaml
    /// </summary>
    public partial class PlayerPage : Window
    {
        private PlayerPageViewModel _playerViewModel;
        public delegate void PageReturnHandler();
        public event PageReturnHandler PageReturn;
        public bool IsSelected { get; set; }
        public string PlayerName { get; set; }

        public PlayerPage()
        {
            InitializeComponent();

            _playerViewModel = new PlayerPageViewModel();
            _playerViewModel.RequestClose += _playerViewModel_RequestClose;
            DataContext = _playerViewModel;
        }

        void _playerViewModel_RequestClose(object sender, System.EventArgs e)
        {
            IsSelected = _playerViewModel.IsSelected;
            PlayerName = _playerViewModel.PlayerName;
            Close();
            if (PageReturn != null)
            {
                PageReturn();
            }
        }

        public void Initialize(MainFrame mf, string id)
        {
            _playerViewModel.Initialize(mf, id);
            FocusManager.SetFocusedElement(this, myBox);
        }

        private void myBox_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                _playerViewModel.SelectCommand.Execute(sender);
            }
            else if (e.Key == Key.Escape)
            {
                _playerViewModel.CancelCommand.Execute(sender);
            }
        }

        private void MyBox_OnLoaded(object sender, RoutedEventArgs e)
        {
            var tBox = sender as TextBox;
            if (tBox != null)
            {
                tBox.SelectAll();
            }
        }
    }
}
